/**
 * Created by liangqinli on 2016/12/19.
 */
const express = require('express');
// const bodyParser = require('body-parser')
const proxy = require('http-proxy-middleware') // require('http-proxy-middleware');
const fs = require('fs')
const httpProxy = require('http-proxy')
const app = express();

const authLoginProxy = proxy({
  target: 'https://us-uat-mycis.synnex.org',
  ssl: {
    key: fs.readFileSync('./ssl/p1-dev1.key'),
    cert: fs.readFileSync('./ssl/p1-dev1.cer')
  },
  changeOrigin: true,
  secure: false,
  logLevel: 'debug',
  // cookieDomainRewrite: {
  //   '*': 'us-uat-mycis.synnex.org'
  // },
  // headers: { host: 'https://us-uat-mycis.synnex.org' }
})
const jsonPlaceholderProxy = proxy({
  target: 'https://us-uat-mycis.synnex.org',
  changeOrigin: true,
  logLevel: 'debug',
  // protocolRewrite: 'https',
  // cookieDomainRewrite: {
  //   '*': 'us-uat-mycis.synnex.org'
  // },
  // headers: { host: 'https://us-uat-mycis.synnex.org' }
})
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
// app.use(bodyParser.urlencoded({ extended: false }));
// app.use(bodyParser.json())
// console.log('jsonPlaceholderProxy', jsonPlaceholderProxy)
app.use('/auth-server', authLoginProxy)
app.use('/sales-order-portal', jsonPlaceholderProxy)
app.use((req, res, next) => {
  console.log('req res req ', req, res)
  next()
})

app.get('/', function (req, res) {
  res.send('welcome mock-data-server');
})
app.get('/test-json', function (req, res) {
  res.json({
    test: 'this is a Fetch json test!'
  })
});



app.listen(3030);
let cookieArr = [];
const proxy1 = httpProxy.createServer({
  ssl: {
    key: fs.readFileSync('./ssl/p1-dev1.key'),
    cert: fs.readFileSync('./ssl/p1-dev1.cer')
  },
  target: 'https://us-uat-mycis.synnex.org',
  secure: false,
  changeOrigin: true,
  cookieDomainRewrite: 'localhost',
  hostRewrite: 302,
  autoRewrite: true,
}).listen(443);
proxy1.on('proxyRes', function (proxyRes, req, res) {
  console.log(proxyRes.headers['set-cookie'], 'aaaaaaaaaaaaaaaaaaaa' ,res)
  let resCookie = proxyRes.headers['set-cookie'] || []
  if (typeof resCookie[0] === 'string') {
    if (cookieArr.find((item) => item === resCookie[0])) return
    if (resCookie[0].indexOf('synnex-sso') > -1) {
      cookieArr.find((item, index) => {
        if(item.indexOf('synnex-sso') > -1) {
          cookieArr[index] = resCookie[0]
          return true
        }
      })
      return
    }
    cookieArr.push(resCookie[0])
  }
})
proxy1.on('proxyReq', function(proxyReq, req, res, option){
  // if (proxyReq) {
  //   proxyReq.setHeader('Cookie', cookieArr)
  // }
  // proxyReq.setHeader('Cookie', cookieArr)
  console.log('ddd')
})
console.log('listen to http://localhost:3030', new Date().toString());

// httpProxy.createProxyServer({
//   target: {
//     protocol: 'https:',
//     host: 'localhost',
//     port: 443,
//     pfx: fs.readFileSync('path/to/certificate.p12'),
//     passphrase: 'password',
//   },
//   changeOrigin: true,
// }).listen(8000);